<template>
  <div class="container">
    <headerBar :title="local.logisticsDetail" @changeLan="changeLan" @pageReturn="pageReturn"></headerBar>
    <div :style="{paddingTop: pdt+'px'}" class="all" style="padding-bottom: 120rpx;">
      <!--物流信息-->
      <div class="top">
        <div class="select-panel">
          <div class="panel-goods">
            <span class="name" :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'">
              <span style="color: red;">*</span>
              {{local.logisticsOrderNo}}：
            </span>
            <div class style="border-bottom: 2rpx solid;flex:1;">
              <input :value="pageData.trackNumber" :placeholder="local.peleaseEnter" />
              <!-- 物流单号 -->
            </div>
          </div>
          <div class="panel-goods">
            <div
              class="name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >{{local.businessDate}}：</div>
            <picker
              class="weui-btn"
              mode="date"
              disabled
              :value="pageData.busDate"
              start="1999-01-01"
              end="2099-01-01"
              @change="TimeChange"
            >
              <!-- 业务日期 -->
              <input disabled :value="busDateFormat" :placeholder="local.peleaseEnter" />
            </picker>
          </div>
          <div class="panel-goods">
            <div class="name" :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'">{{local.status}}：</div>
            <div class="names-goods">{{pageData.status == 'PASS'?local.reviewed:local.notSaved}}</div>
          </div>
        </div>
        <div class="select-panel">
          <div class="panel-goods">
            <div class="name" :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'">
              <span style="color: red;">*</span>
              {{local.bookingNumber}}：
            </div>
            <div class style="border-bottom: 2rpx solid;flex:1;">
              <input disabled :value="pageData.bookingNo" :placeholder="local.peleaseEnter" />
              <!-- <input disabled v-model="logisticsObj.bookingNo" :placeholder="local.peleaseEnter" /> -->
            </div>
          </div>
          <div class="panel-goods">
            <div class="name" :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'">
              <span style="color: red;">*</span>
              {{local.boxCount}}：
            </div>
            <div
              class
              style="border-bottom: 2rpx solid;flex:1;display: flex;justify-content: space-between;"
            >
              <input disabled :value="pageData.boxCount" :placeholder="local.peleaseEnter" />
              <span class="unit">{{local.boxUnit}}</span>
            </div>
          </div>
          <div class="panel-goods">
            <div
              class="name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >{{local.beltType}}：</div>
            <div class style="border-bottom: 2rpx solid;flex:1;">
              <input
                disabled
                :value="pageData.beltType == '4'? local.otherBeltType:pageData.beltTypeName"
                :placeholder="local.peleaseEnter"
              />
            </div>
          </div>
          <div class="panel-goods" v-if="pageData.beltType == '4'">
            <div
              class="name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >{{local.beltTypeName}}：</div>
            <div class style="border-bottom: 2rpx solid;flex:1;">
              <input disabled :value="pageData.beltTypeName" :placeholder="local.peleaseEnter" />
            </div>
          </div>
          <div class="panel-goods">
            <div
              class="name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >{{local.boxType}}：</div>
            <div class style="border-bottom: 2rpx solid;flex:1;">
              <input
                disabled
                :value="pageData.boxType == '3'? local.otherBoxType:pageData.boxTypeName"
                :placeholder="local.peleaseEnter"
              />
            </div>
          </div>
          <div class="panel-goods" v-if="pageData.boxType == '3'">
            <div
              class="name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >{{local.boxType}}：</div>
            <div class style="border-bottom: 2rpx solid;flex:1;">
              <input disabled :value="pageData.boxTypeName" :placeholder="local.peleaseEnter" />
            </div>
          </div>
          <div class="panel-goods">
            <div class="name" :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'">{{local.shipNo}}：</div>
            <div class style="border-bottom: 2rpx solid;flex:1;">
              <input disabled :value="pageData.boxTypeName" :placeholder="local.peleaseEnter" />
            </div>
          </div>
          <div class="panel-goods">
            <div class="name" :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'">
              <span style="color: red;">*</span>
              {{local.closingDate}}：
            </div>
            <picker
              disabled
              class="weui-btn"
              mode="date"
              :value="pageData.sectionalCabinetTime"
              start="1999-01-01"
              end="2099-01-01"
              @change="TimeChangeSectional"
            >
              <input disabled :value="sectionalCabinetTimeFormat" :placeholder="local.option" />
            </picker>
          </div>
        </div>
        <div class="select-panel">
          <div class="panel-goods">
            <div class="name" :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'">
              <span style="color: red;">*</span>
              {{local.workshopStaff}}：
            </div>
            <div class="page" style="border-bottom: 2rpx solid;flex:1;position: relative">
              <picker
                disabled
                class="weui-btn"
                @change="PickerUserChange"
                :value="indexUserPicker"
                :range="carUserList"
                :range-key="'userName'"
              >
                <input
                  disabled
                  type="default"
                  :value="pageData.userName"
                  :placeholder="local.option"
                />
                <span class="unit">▼</span>
              </picker>
            </div>
          </div>
        </div>
        <div class="select-panel">
          <div class="panel-goods">
            <div
              class="name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >{{local.departureDate}}：</div>
            <picker
              disabled
              class="weui-btn"
              mode="date"
              :value="pageData.departTime"
              start="1999-01-01"
              end="2099-01-01"
            >
              <input disabled :value="departTimeFormat" :placeholder="local.peleaseEnter" />
            </picker>
          </div>
          <div class="panel-goods">
            <div class="name" :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'">
              <span style="color: red;">*</span>
              {{local.portOfDeparture}}：
            </div>
            <div class style="border-bottom: 2rpx solid;flex:1;">
              <input disabled :value="pageData.departHarbor" :placeholder="local.peleaseEnter" />
            </div>
          </div>
          <div class="panel-goods">
            <div class="name" :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'">
              <span style="color: red;">*</span>
              {{local.portOfDestination}}：
            </div>
            <div class style="border-bottom: 2rpx solid;flex:1;">
              <input disabled :value="pageData.purposeHarbor" :placeholder="local.peleaseEnter" />
            </div>
          </div>
        </div>
        <div class="select-panel">
          <div class="panel-goods">
            <div
              class="name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >{{local.shippingCompany}}：</div>
            <div class style="border-bottom: 2rpx solid;flex:1;">
              <input disabled :value="pageData.shippingCompany" :placeholder="local.peleaseEnter" />
            </div>
          </div>
          <div class="panel-goods">
            <div class="name" :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'">{{local.shipNo}}：</div>
            <div class style="border-bottom: 2rpx solid;flex:1;">
              <input
                disabled
                :value="pageData.shippingCompanyNumber"
                :placeholder="local.peleaseEnter"
              />
            </div>
          </div>
          <div class="panel-goods">
            <div
              class="name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >{{local.arrivalDate}}：</div>
            <picker
              disabled
              class="weui-btn"
              mode="date"
              :value="date"
              start="1999-01-01"
              end="2099-01-01"
            >
              <input disabled :value="arriveTimeFormat" :placeholder="local.peleaseEnter" />
            </picker>
          </div>
        </div>
      </div>

      <div class="blueTitle">{{local.commodityInformation}}:</div>
      <div style="padding-bootpm: 120rpx;">
        <!--商品信息-->
        <div v-for="(item, i) in goodsList" :key="i">
          <div class="select-panel">
            <div class="opreate jt_flex jt_flex_row_right">
              <div
                class="open"
                @click="openOrClose(goodsList,i,'goods')"
              >{{item.open ? local.fold : local.unfold}}</div>
              <div
                class="detele-text"
                @click="deleteRow(goodsList,i,'goods')"
              >{{local.deletesingle}}</div>
            </div>
            <div class="panel-goods">
              <div class="name" :class="lang == 'zh'?'w_85':'w_110'">{{local.goodsName}}：</div>
              <div class="names-goods">{{item.goodsName}}</div>
            </div>
            <div class="panel-goods">
              <div class="name" :class="lang == 'zh'?'w_85':'w_110'">{{local.buyArea}}：</div>
              <div class="names-goods">{{item.buyAreaName || ''}}</div>
            </div>
            <div class="panel-goods">
              <div class="name" :class="lang == 'zh'?'w_85':'w_110'">{{local.warehouseOut}}：</div>
              <div class="names-goods">{{item.warehouseName}}</div>
            </div>
            <div class="panel-goods">
              <div class="name" :class="lang == 'zh'?'w_85':'w_110'">{{local.isThereWood}}：</div>
              <picker
                class="weui-btn"
                style="border-bottom: 2rpx solid;width: 100%;"
                @change="PickerWoodChange"
                :value="item.isWoodiness*1-1"
                :id="i"
                :range="arrayWood"
                :range-key="'label'"
              >
                <input
                  disabled
                  :value="arrayWood[item.isWoodiness-1].label"
                  type="default"
                  :placeholder="local.option"
                />
                <span class="unit"></span>
              </picker>
            </div>
            <div class="panel-goods">
              <div class="name" :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'">
                <span style="color: red;width: 2rpx;margin-right:12rpx">*</span>
                {{local.containerNumber}}：
              </div>
              <div class style="border-bottom: 2rpx solid;width: calc(100% - 82px)">
                <input
                  @change="containerNumberChange"
                  :adjust-position="adjustPosition"
                  :data-index="i"
                  :placeholder="local.peleaseEnter"
                  v-model="item.containerNumber"
                  :disabled="disabledEdit"
                />
              </div>
            </div>
          </div>
          <div class="select-panel" v-if="item.open">
            <div class="panel-goods">
              <div
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.grade}}：</div>
              <div class="names-goods">{{item.goodsLevelName}}</div>
            </div>
            <div class="panel-goods">
              <div
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.beltType}}：</div>
              <div class="names-goods">{{item.beltTypeName}}</div>
            </div>
          </div>
          <div class="stock-detail-panel" v-if="item.open">
            <div class="msg-detail-thickness">
              <span
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.thickness}}：</span>
              <div class style="border-bottom: 2rpx solid;">
                <input :placeholder="local.peleaseEnter" disabled v-model="item.sizeHeight" />
                <span class="unit">MM</span>
              </div>
            </div>
            <div class="msg-detail-width">
              <span
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.width}}：</span>
              <div class style="border-bottom: 2rpx solid;">
                <input :placeholder="local.peleaseEnter" disabled v-model="item.sizeWidth" />
                <span class="unit">MM</span>
              </div>
            </div>
            <div class="msg-detail-long">
              <span
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.length}}：</span>
              <div class style="border-bottom: 2rpx solid;">
                <input :placeholder="local.peleaseEnter" disabled v-model="item.sizeLong" />
                <span class="unit">M</span>
              </div>
            </div>
            <div class="msg-detail-long">
              <span
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.weight}}：</span>
              <div class style="border-bottom: 2rpx solid;">
                <input :placeholder="local.peleaseEnter" disabled v-model="item.weight" />
                <span class="unit">T</span>
              </div>
            </div>
          </div>
          <div
            class="select-photo"
            v-if="item.beginPicUrlList && item.beginPicUrlList.length && item.open"
          >
            <div class="a">{{local.photosBeforeAcceptance}}</div>
            <div class="b">
              <div class="page">
                <div class="weui-uploader__bd">
                  <div class="weui-uploader__files" id="uploaderFiles">
                    <block v-for="(element, index) in item.beginPicUrlList" :key="index">
                      <div
                        class="weui-uploader__file"
                        @click="predivImage"
                        :id="element"
                        :data-urls="item.beginPicUrlList"
                      >
                        <img
                          class="weui-uploader__img"
                          :src="Shop.IMG_URL+element"
                          mode="aspectFill"
                        />
                      </div>
                    </block>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div
            class="select-photo"
            v-if="item.endPicUrlList && item.endPicUrlList.length && item.open"
          >
            <div class="a">{{local.photosAfterAcceptance}}</div>
            <div class="b">
              <div class="page">
                <div class="weui-uploader__bd">
                  <div class="weui-uploader__files" id="uploaderFiles">
                    <block v-for="(element, index) in item.endPicUrlList" :key="index">
                      <div
                        class="weui-uploader__file"
                        @click="predivImage"
                        :id="element"
                        :data-urls="item.endPicUrlList"
                      >
                        <img
                          class="weui-uploader__img"
                          :src="Shop.IMG_URL+element"
                          mode="aspectFill"
                        />
                      </div>
                    </block>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="remark" v-if="item.open">
            <div>{{local.remark}}:</div>
            <textarea
              v-model="item.remark"
              disabled
              style="height: 100rpx;max-width: 879rpx;resize: none;"
            ></textarea>
          </div>
        </div>
        <div
          class="add-btn"
          v-if="pageData.status != 'PASS'"
          @click="addLogisGood"
        >+ {{local.continueAdding}}</div>
        <!-- 继续添加 商品 -->
        <!-- 装箱出库 -->
        <div style="margin: 44rpx auto 10rpx 20rpx;font-size: 36rpx;">{{local.packingOut}}</div>
        <div class="blueTitle">{{local.logisticsInformation}}:</div>
        <div v-for="(item, i) in encasementList" :key="i">
          <div class="stock-detail-panel">
            <div class="opreate jt_flex jt_flex_row_right">
              <div
                class="open"
                @click="openOrClose(encasementList,i,'encasement')"
              >{{item.open ? local.fold : local.unfold}}</div>
              <div
                class="detele-text"
                @click="deleteRow(encasementList,i,'encasement')"
              >{{local.deletesingle}}</div>
            </div>
            <div class="msg-detail-thickness">
              <span
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.containerNumber}}：</span>
              <picker
                class="weui-btn"
                style="border-bottom: 2rpx solid;width: 100%;"
                :disabled="disabledEdit"
                @change="PickerContainerChange"
                :data-i="i"
                :range="containerNumberList"
                :value="indexContainerPicker"
              >
                <!-- v-model="arrayContainer[indexContainerPicker]" -->
                <input
                  disabled
                  type="default"
                  :value="item.containerNumber"
                  :placeholder="local.option"
                />
                <span class="unit"></span>
              </picker>
            </div>
            <div class="msg-detail-width">
              <span
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.goodsTotal}}：</span>
              <div class style="border-bottom: 2rpx solid;">
                <input v-model="item.goodsCount" :placeholder="local.peleaseEnter" disabled />
                <span class="unit"></span>
              </div>
            </div>
            <div class="stock-detail-belt">
              <span
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.lockNumber}}：</span>
              <div class style="border-bottom: 2rpx solid;">
                <input
                  v-model="item.lockNumber"
                  :adjust-position="adjustPosition"
                  :placeholder="local.peleaseEnter"
                  :disabled="disabledEdit"
                />
              </div>
            </div>
            <div class="stock-detail-belt">
              <span
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.stevedores}}：</span>
              <div class style="border-bottom: 2rpx solid;">
                {{item.userName}}
              </div>
            </div>
          </div>
          <div class="select-photo" v-if="item.open">
            <div class="a">{{local.photosBeforePacking}}</div>
            <div class="b">
              <div class="page">
                <div class="weui-uploader__bd">
                  <div class="weui-uploader__files" id="uploaderFiles">
                    <block v-for="(element,index) in item.beginPicUrlList" :key="index">
                      <div
                        class="weui-uploader__file"
                        @click="predivImage"
                        :id="element"
                        :data-urls="item.beginPicUrlList"
                      >
                        <img
                          class="weui-uploader__img"
                          :src="Shop.IMG_URL + element"
                          mode="aspectFill"
                        />
                        <div
                          class="detele-img"
                          @click="deleteImg(element, index,i, 'beginPic')"
                        >{{local.deletesingle}}</div>
                      </div>
                    </block>
                    <div class="weui-uploader__input-box" v-if="pageData.status != 'PASS'">
                      <div
                        class="weui-uploader__input"
                        @click="imageUpload(encasementList,i,'beginPicUrlList','beginTime')"
                      ></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="stock-detail-panel" v-if="item.open">
            <div class="msg-detail-thickness">
              <span
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.boxWeight}}：</span>
              <div class style="border-bottom: 2rpx solid;">
                <input
                  type="digit"
                  v-model="item.weight"
                  :adjust-position="adjustPosition"
                  :placeholder="local.peleaseEnter"
                  :disabled="disabledEdit"
                />
                <span class="unit">T</span>
              </div>
            </div>
            <div class="msg-detail-thickness">
              <span
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.totalWeight}}：</span>
              <div class style="border-bottom: 2rpx solid;">
                <input
                  v-model="item.totalWeight"
                  :adjust-position="adjustPosition"
                  :placeholder="local.peleaseEnter"
                  disabled
                />
                <span class="unit">T</span>
              </div>
            </div>
            <div class="msg-detail-thickness">
              <span
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.weighingNumber}}：</span>
              <div class style="border-bottom: 2rpx solid;">
                <input
                  v-model="item.weighCode"
                  :adjust-position="adjustPosition"
                  :placeholder="local.peleaseEnter"
                  :disabled="disabledEdit"
                />
              </div>
            </div>
            <div class="msg-detail-width">
              <span
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.weighingWeight}}：</span>
              <div class style="border-bottom: 2rpx solid;">
                <input
                  v-model="item.weigh"
                  @input="changeDifference"
                  :placeholder="local.peleaseEnter"
                  :data-i="i"
                  type="digit"
                  :adjust-position="adjustPosition"
                  :disabled="disabledEdit"
                />
                <span class="unit">T</span>
              </div>
            </div>
            <div class="msg-detail-width">
              <span
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
              >{{local.WeighingAndTotalWeightDifference}}：</span>
              <div class style="border-bottom: 2rpx solid;">
                <input
                  v-model="item.weightDifference"
                  :adjust-position="adjustPosition"
                  :placeholder="local.peleaseEnter"
                  disabled
                />
                <span class="unit">T</span>
              </div>
            </div>
          </div>
          <div class="select-photo" v-if="item.open">
            <div class="a">{{local.photosAfterPacking}}</div>
            <div class="b">
              <div class="page">
                <div class="weui-uploader__bd">
                  <div class="weui-uploader__files" id="uploaderFiles">
                    <block v-for="(element,index) in item.endPicUrlList" :key="index">
                      <div
                        class="weui-uploader__file"
                        @click="predivImage"
                        :id="element"
                        :data-urls="item.endPicUrlList"
                      >
                        <img
                          class="weui-uploader__img"
                          :src="Shop.IMG_URL + element"
                          mode="aspectFill"
                        />
                        <div
                          class="detele-img"
                          @click="deleteImg(element, index,i, 'endPic')"
                        >{{local.deletesingle}}</div>
                      </div>
                    </block>
                    <div class="weui-uploader__input-box" v-if="pageData.status != 'PASS'">
                      <div
                        class="weui-uploader__input"
                        @click="imageUpload(encasementList,i,'endPicUrlList','endTime')"
                      ></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div
          class="add-btn"
          v-if="pageData.status != 'PASS'"
          @click="addPacking(encasementList)"
          style="margin-bottom: 121rpx;"
        >+ {{local.continueAdding}}</div>
        <!-- 继续添加 装箱 -->
        <div class="bottom-bar">
          <ul class="tip mr_20">
            <li>{{local.commodityInformation}}:{{goodsList.length}}</li>
            <li>{{local.logisticsInformation}}:{{encasementList.length}}</li>
          </ul>
          <div
            class="confirm-b"
            @click="saveSplitOrder"
            v-if="pageData.status != 'PASS'"
          >{{local.saveSplitOrder}}</div>
          <div class="confirm-b" @click="saveEdit" v-if="pageData.status != 'PASS'">{{local.submit}}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import home from '@/api/home'
import headerBar from '@/components/headerBar'
import { dictMatching, formatDate, previewImage,unique } from '@/utils/index'
import Shop from '../../../../config/shop'
var a
export default {
  components: {
    headerBar
  },
  methods: {
    addLogisGood () {
      this.routerToUrl('../../pages/selectGoods/index?page=' + 'logis')
      },
    pageReturn () {
      wx.setStorageSync('selectLogisicList', [])
    },
    initLang(){
      this.local = wx.getStorageSync('local')
      this.lang = wx.getStorageSync('lang')
    },
    getEncasementIndex(){
      let encasementIndex = -1
        this.encasementList.forEach((enc, eIndex) => {
          this.goodsList.forEach(good => {
            if(enc.containerNumber == good.containerNumber){
              encasementIndex = eIndex
            }
          })
        })
        return encasementIndex
    },
    //商品信息的集装箱号
    containerNumberChange(e){
      let num = e.mp.detail.value
      let index = e.currentTarget.dataset.index
      //更新 装箱信息中的集装箱号列表
      this.containerNumberList = [...new Set(this.goodsList.map(item => item.containerNumber))]
      let encasementIndex = this.getEncasementIndex()
      if(this.encasementList.some(item => item.containerNumber == num)){
        //输入的商品集装箱号，更新集装箱中的信息
         let totalWeigh = this.encasementList[encasementIndex].weigh + this.goodsList[index].weight //商品的集装箱号变更后，过磅重量
      } else {
          if(encasementIndex == -1){
            this.encasementList.splice(0,1)
            return
          }
          //没有相同的集装箱号，更新集装箱中的信息
          this.updateEncasementData(encasementIndex,this.encasementList[encasementIndex].weigh)
        }
        this.containerNumberList.forEach(num=>{
          this.updateBoxNum(num)
        })
    },
    updateEncasementData(encasementIndex,totalWeigh){
        let goodsList = this.goodsList.filter(item => item.containerNumber == this.encasementList[encasementIndex].containerNumber)
        this.encasementList[encasementIndex].goodsCount = goodsList.reduce((prev,next) => { return prev + next.goodsCount},0)
        this.getEncasementData(encasementIndex,totalWeigh,this.encasementList[encasementIndex].containerNumber)
    },
    //删除商品或装箱
    deleteRow(list,index,type){
      //最后一个不能被删除
      if(list.length == 1) {
        let title  = {
            goods:'最后一个商品不能被删除',
            encasement:'最后一个集装箱不能被删除'
        }[type]
        wx.showToast({
          title,
          icon: 'none',
          duration: 2000
        })
        return
      }
      const row = list[index]//删除行的数据
      const {
        containerNumber,
      } = row //被删除的集装箱号
        
      if(type == 'goods'){
        const arr = wx.getStorageSync('selectLogisicList')
        // 提取本地缓存的id信息
        const id = list[index].goodsId || list[index].id
        // 提取删除的商品id 新添加的商品id为goodsId  保存后的id字段为id  真是难以理解之前的编码的脑回路
        const h = arr.filter(item => item !== id)
        // 记录删除后的Id信息  应该是为了确保保存的数据无出入吧？
        wx.setStorageSync('selectLogisicList',h)


        const { weight } = row
        this.goodsList.splice(index,1)//删除商品

        // 商品清除结束,开始关联
        let encasementIndex = -1
        const encasement = this.encasementList.find((item,i) => {
          encasementIndex = i
          return item.containerNumber == containerNumber
        })
        // 查询集装箱
        if(encasement){
            // 查询到集装箱信息
            if(encasement.length == 1){
                // 如果 集装箱信息对应只剩余1个,那么清除装箱信息
              this.encasementList.splice(encasementIndex,1)
              return
            }else{
              encasement.goodsCount-- //商品数量自减1
              encasement.totalWeight = list.reduce((prev,{weight})=> prev + (weight * 1),0).toFixed(2)
              this.getEncasementData(encasementIndex,encasement.totalWeight,encasement.containerNumber)
            }
        }
      }else {
        this.encasementList.splice(index,1)
      }
      this.updateBoxNum(containerNumber)
    },
    openOrClose(list, index,type) {
      console.log(
        this.goodsList
      );
      if(type == 'encasement'){
        if(list[index].containerNumber == ''){
          wx.showToast({
            title: '请选择集装箱号',
            duration: 2000,
            icon: 'none'
          })
          return
        }
      }
      list[index].open = !list[index].open
      list.push()
    },
    deleteImg(ite, index, i, type) {
      if (type == "beginPic") {
        this.encasementList[i].beginPicUrlList = this.encasementList[
          i
        ].beginPicUrlList.filter(item => item != ite)
      } else {
        this.encasementList[i].endPicUrlList = this.encasementList[
          i
        ].endPicUrlList.filter(item => item != ite)
      }
    },
    getSubmitData(check = true){
    // check 是否校验
     if(this.goodsList.length == 0){
        wx.showToast({
          title: this.local.addPackGoodsTip,
          icon: 'none',
          duration: 2000
        })
        return
     }
     //必须集装箱被全部使用
     let list = [...new Set(this.goodsList.map(item => item.containerNumber))]
     let packList = [...new Set(this.encasementList.map(item => item.containerNumber))]
     console.log(
       list,packList
     );
      if(check && list.length !== packList.length){
        wx.showToast({
          title: this.local.packInfoTip,
          icon: 'none',
          duration: 2000
        })
        return
      }
      const validatorGoodsList = this.validatorGoodsList() //获取校验未通过清单
      const validatorEncasementList = this.validatorEncasementList() //获取校验未通过清单
      console.log(validatorEncasementList);
      let {
        local: {
          missingRequiredParameters,
          containerNumber,
          goodsCount,
          lockNumber,
          totalWeight,
          total,
          weighingWeight,
          WeighingAndTotalWeightDifference,
          photosBeforePacking,
          photosAfterPacking
        }
      } = this
      if (check && validatorGoodsList.length) {
        wx.showToast({
          title: `商品信息${missingRequiredParameters}:${containerNumber}`,
          duration: 2000,
          icon: 'none'
        })
        return
      }
      if (check && validatorEncasementList.length) {
        wx.showToast({
          title: `物流信息${missingRequiredParameters}:
                  ${goodsCount}、${lockNumber}、${totalWeight}、${total}、${weighingWeight}、${WeighingAndTotalWeightDifference}、${photosBeforePacking}、${photosAfterPacking}
            `,
          duration: 4000,
          icon: 'none'
        })
        return
      }
      let data = JSON.parse(
        JSON.stringify(this.pageData).replace(/null/g, '""')
      )
      data.goodList = JSON.stringify(data.goodsList)
      data.encasementLists = JSON.stringify(data.encasementList)
      delete data.goodsList
      delete data.encasementList
      return data
},
    saveSplitOrder(){
        const data = this.getSubmitData(false)
        if(data){
        home
        .saveLogisticsManageList(data)
        .then(res => {
          if(res.code != 0){
             wx.showToast({
              title: res.msg || 'error',
              duration: 1000,
              icon: 'none'
            })
            return
          }
          wx.showToast({
            title: `${this.local.success}`,
            duration: 1000,
            icon: 'success'
          })
          wx.redirectTo({
            url: '../../pages/logistics/index'
          })
        })
        .catch(e => {
          wx.showToast({
            title: `${this.local.error}`,
            duration: 1000,
            icon: 'none'
          })
        })

        }
    },
    saveEdit() {
    const data = this.getSubmitData()
    if(data){
        home
        .editLogisticsManageList(data)
        .then(res => {
          if(res.code != 0){
             wx.showToast({
              title: res.msg || 'error',
              duration: 1000,
              icon: 'none'
            })
            return
          }
          wx.showToast({
            title: `${this.local.success}`,
            duration: 1000,
            icon: 'success'
          })
          wx.redirectTo({
            url: '../../pages/logistics/index'
          })
        })
        .catch(e => {
          wx.showToast({
            title: `${this.local.error}`,
            duration: 1000,
            icon: 'none'
          })
        })
    }
      
    },
    validatorEncasementList() {
      return this.encasementList.filter(item => {
        item.beginPicUrl = item.beginPicUrlList.join()
        item.endPicUrl = item.endPicUrlList.join()
        let necessaryList = [
          'containerNumber',
          'goodsCount',
          'lockNumber',
          'totalWeight',
          'weigh',
          'weight',
          'weightDifference',
          'beginPicUrl',
          'endPicUrl'
        ]
        console.log(necessaryList.find(element => {
          return !item.hasOwnProperty(element) || item[element] === ''
        }));
        return necessaryList.some(element => {
          return !item.hasOwnProperty(element) || item[element] === ''
        })
      })
    },
    validatorGoodsList() {
      return this.goodsList.filter((item, index) => {
        item.index = index
        let { containerNumber, isWoodiness } = item
        return (
          containerNumber === '' ||
          containerNumber === undefined ||
          isWoodiness === '' ||
          isWoodiness === undefined
        )
      })
    },
    affirmLogistics(id){
      home
        .affirmLogistics({ id: id })
        .then(res => {
          if(res.code != 0) {
            wx.showToast({
              title: res.msg || 'error',
              duration: 2000,
              icon: 'none'
            })
          }
        })
    },
    getPageData(option) {
      const { id } = option
      //获取当前页面数据方法
      wx.showLoading({
        title: this.local.loading,
        mask: true
      })
      home
        .getLogisticsListId(option)
        .then(res => {
          wx.hideLoading()
          this.pageData = res
          this.goodsList = this.pageData.goodsList
          // this.goodsId = this.pageData.goodsId
          let arr = []
          this.goodsList.map((item) => {
            arr.push(Number(item.goodsId))
          })
          wx.setStorageSync('selectLogisicList', arr)
          this.encasementList = this.pageData.encasementList
          this.pageData.busDate = this.pageData.busDate.substring(0, 10)
          this.pageData.sectionalCabinetTime = this.pageData.sectionalCabinetTime == null ? '':this.pageData.sectionalCabinetTime.substring(0, 10)
          this.pageData.departTime = this.pageData.departTime == null ? '':this.pageData.departTime.substring(0, 10)
          this.pageData.arriveTime = this.pageData.arriveTime == null ? '':this.pageData.arriveTime.substring(0, 10)
          this.disabledEdit = this.pageData.status == 'PASS'?true:false
          this.goodsList.map(item => {
            let { beginPicUrl, endPicUrl } = item
            item.goodsCount = 1  //商品数量默认1
            item.beginPicUrlList = beginPicUrl ? beginPicUrl.split(',') : []
            item.endPicUrlList = endPicUrl ? endPicUrl.split(',') : []
            item.goodsLevelName = dictMatching(
              wx.getStorageSync('goodsLevel') || [],
              item.goodsLevel
            )
            item.beltTypeName = dictMatching(
              wx.getStorageSync('beltType') || [],
              item.beltType
            )
          })
          this.encasementList.map(item => {
            let { beginPicUrl, endPicUrl, containerNumber } = item
            this.containerNumberList.push(containerNumber)
            item.isAdd = 1 //不是新增的集装箱
            item.beginPicUrlList = beginPicUrl ? beginPicUrl.split(',') : []
            item.endPicUrlList = endPicUrl ? endPicUrl.split(',') : []
          })
        })
        .catch(e => {
          console.log(e)
        })
    },
    //装箱信息中
    getCountAddWeight(containerNumber) {
      //相同集装箱号的商品总数、总重汇总
      let list = this.goodsList.filter(
        item => item.containerNumber == containerNumber
      )
      let total = 0
      let totalWeight = 0
      list.map(item => {
        total += item.goodsCount
        totalWeight += item.weight
      })
      return { total, totalWeight }
    },
    changeDifference(e) {
      //过磅和总重差
      let weigh = Number(e.mp.detail.value) || 0
      let containerNumber = this.encasementList[e.mp.target.dataset.i]
        .containerNumber
      let totalWeight = this.getCountAddWeight(containerNumber).totalWeight
      this.encasementList[e.mp.target.dataset.i].weightDifference = Math.abs(
        weigh - totalWeight
      ).toFixed(2)
    },
    PickerWoodChange(e) {
      //有无木质修改方法
      let value = e.mp.detail.value
      let index = e.mp.target.id
      this.goodsList[index].isWoodiness = this.arrayWood[value].value
      this.goodsList.push()
    },
    PickerContainerChange(e) {
      //修改集装箱号
      let index = e.mp.currentTarget.dataset.i
      let value = e.mp.detail.value
      this.indexContainerPicker = e.mp.detail.value
      let containerNumber = this.containerNumberList[e.mp.detail.value]
      this.encasementList[index].containerNumber = this.goodsList[index].containerNumber
      this.encasementList[index].goodsCount = this.getCountAddWeight(containerNumber).total
      this.encasementList[index].totalWeight = this.getCountAddWeight(containerNumber).totalWeight.toFixed(2)
      this.encasementList.push()
    },
    imageUpload(list, index, type,timeType) {
      a = true
      let data = list[index][type]
      //图片上传方法
      if(type == 'endPicUrlList' && list[index].beginPicUrlList.length == 0){
        wx.showToast({
          title: this.local.PleaseUploadPhotosBeforePacking,
          duration: 4000,
          icon: 'none'
        })
        return
      }
      wx.chooseImage({
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: res => {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          // data[type].concat(res.tempFilePaths)
          res.tempFilePaths.map((item, index) => {
            wx.uploadFile({
              url: `${Shop.BASE_URL}applet/buy/storage/common/upload`,
              filePath: item, // chooseImage上传的图片
              name: 'file', // 需要传给后台的图片字段名称
              formData: item, // 需要传给后台的其他表单数据
              header: {
                Authorization: wx.getStorageSync('token')
              },
              success: res => {
                if (res.statusCode == 200) {
                  let { code, url, msg } = JSON.parse(res.data)
                  if (code == 0) {
                    var myDate = new Date()
                    let time = formatDate(myDate, 'YYYY-MM-DD HH:ii:SS')         
                    data.push(url)
                    list[index][timeType] = time
                    list.push()
                  } else {
                    wx.showToast({
                      title: msg,
                      duration: 4000,
                      icon: 'none'
                    })
                  }
                } else {
                  wx.showToast({
                    title: _this.local.uploadFail,
                    duration: 4000,
                    icon: 'none'
                  })
                }
              }
            })
          })
        },
        fail: function() {},
        complete: function() {}
      })
    },
    routerToUrl(url) {
      //页面跳转
      wx.navigateTo({
        url
      })
    },
    filterContainerNumber(data){
      // 预防数据
      this.containerNumberList = [...new Set(this.goodsList.filter(item=> item.containerNumber).map(item=> item.containerNumber ))]
      this.containerNumberList = this.containerNumberList.filter(item => !data.map(enc => enc.containerNumber).includes(item))
    },
    addPacking(data) {
      //集装箱号必填
      let flag = this.goodsList.some(item => item.containerNumber == "")
      if (flag) {
        wx.showToast({
          title: this.local.containerNumberTip,
          icon: "none",
          duration: 2000,
        })
        return
      }
      //过滤已选择的集装箱号
      this.filterContainerNumber(data)
      if(this.containerNumberList.length == 0){
        wx.showToast({
          title: '没有可以添加的集装箱号',
          icon: 'none',
          duration: 2000
        })
        return
      }
      //添加一行
      let num = this.containerNumberList[0]
      let goods = this.goodsList.filter(item => item.containerNumber == this.containerNumberList[0])
      let goodsCount = goods.reduce((prev,next)=>{return prev + next.goodsCount*1},0)
      let totalWeight = goods.reduce((prev,next)=>{return prev + next.weight*1},0).toFixed(2)
      data.push({
        containerNumber: num,
        weight: "",
        goodsCount: goodsCount,
        weigh: "",
        weighCode: "",
        totalWeight: totalWeight,
        weightDifference: "",
        endPicUrl: "",
        beginPicUrl: "",
        endPicUrlList: [],
        beginPicUrlList: [],
        lockNumber: "",
        isAdd: 2 //默认新增2
      })
    },
    changeLan (val, lang) {
      this.local = val
      this.lang = lang
    },
    async getLogisticsListId(id) {
      const data = await home.getLogisticsListId({ id: id })
      this.logisticsObj = data
      if (this.logisticsObj.encasementList.length !== 0) {
        this.logisticsObj.encasementList.map(item => {
          if (typeof item.beginPicUrl == 'string') {
            item.beginPicUrl = item.beginPicUrl.split(',')
          }
          if (typeof item.endPicUrl == 'string') {
            item.endPicUrl = item.endPicUrl.split(',')
          }
        })
      }
      if (this.logisticsObj.goodsList.length !== 0) {
        this.logisticsObj.goodsList.map(item => {
          if (typeof item.beginPicUrl == 'string') {
            item.beginPicUrl = item.beginPicUrl.split(',')
          }
          if (typeof item.endPicUrl == 'string') {
            item.endPicUrl = item.endPicUrl.split(',')
          }
        })
      }
    },
    predivImage(e) {
      a = true
      previewImage(e)
    },
    //选择商品后，在这里获取商品信息
    prevPage(){
      let pages = getCurrentPages()
      let currPage = pages[pages.length - 1] //当前页面
      if (currPage.data.mydata) {
        //没有选择商品，则不添加
        if(currPage.data.mydata.selectGoodsItem == '') return
        let objItem = currPage.data.mydata.selectGoodsItem
        let { beginPicUrl, endPicUrl } = objItem
        objItem.goodsCount = 1 //商品数量默认1
        objItem.beginPicUrlList = beginPicUrl ? beginPicUrl.split(',') : []
        objItem.endPicUrlList = endPicUrl ? endPicUrl.split(',') : []
        objItem.goodsLevelName = dictMatching(
                wx.getStorageSync('goodsLevel') || [],
                objItem.goodsLevel
              )
              objItem.beltTypeName = dictMatching(
                wx.getStorageSync('beltType') || [],
                objItem.beltType
              )
        objItem.isWoodiness = 1
        objItem.containerNumber = this.goodsList.length == 0? '':this.goodsList[this.goodsList.length-1].containerNumber
        // 如果选择了相同商品，这里做一个去重
        this.goodsList.push(objItem)

        //同个集装箱号，商品总数、商品总重、过磅重量、过磅总量差
       let encasementIndex = this.encasementList.findIndex(item => item.containerNumber == objItem.containerNumber)
       if(encasementIndex != -1){
        let goods = this.goodsList.filter(item => item.containerNumber == objItem.containerNumber)
          // goods.forEach(item => this.containerNumberList.push(item.containerNumber))
        this.containerNumberList = [...new Set(this.goodsList.map(item => item.containerNumber))]
        this.filterContainerNumber(this.containerNumberList)
        let goodsCount = goods.reduce((prev, next)=>{ return prev + next.goodsCount*1},0)
        let totalWeigh = objItem.weight + this.encasementList[encasementIndex].weigh*1  //原来的过磅重量+选择的商品重量
        let totalWeight = goods.reduce((prev, next)=>{ return prev + next.weight*1},0).toFixed(2)
        this.encasementList[encasementIndex].goodsCount = goodsCount
        this.getEncasementData(encasementIndex,totalWeigh,objItem.containerNumber)
        this.updateBoxNum(objItem.containerNumber)
       }
        currPage.setData({
          mydata:null
        })
      }
    },
    //
    getEncasementData(encasementIndex,totalWeigh,containerNumber){
      let goods = this.goodsList.filter(item => item.containerNumber == containerNumber)
      let goodsCount = goods.reduce((prev, next)=>{ return prev + next.goodsCount*1},0)
      let totalWeight = goods.reduce((prev, next)=>{ return prev + next.weight*1},0)
      this.encasementList[encasementIndex].totalWeight = totalWeight.toFixed(2)
      this.encasementList[encasementIndex].weigh = totalWeigh
      this.encasementList[encasementIndex].weightDifference = Math.abs(totalWeigh-totalWeight).toFixed(2)
    },
    affirmLogistics(id){
      home
        .affirmLogistics({ id: id })
        .then(res => { 
          if(res.code != 0) {
            wx.showToast({
              title: res.msg || 'error',
              duration: 2000,
              icon: 'none'
            })
          }
        })
    },

    updateBoxNum(num){
      if(num == null)return
      const goodsList = this.goodsList.filter( item => item.containerNumber == num)
      const encasement = this.encasementList.find(item => item.containerNumber == num)
      if(!encasement)return
      const goodsCount = goodsList.length
      let totalWeight = 0
      let userNames = ''
      goodsList.forEach(({weight,userName})=>{
        totalWeight += weight*1
        userName && !userNames.includes(userName) && (userNames += userName)
      })

      // goodsList.reduce((prv,{weight} )=> prv += weight*1,0).toFixed(2)
      Object.assign(encasement,{
        weightDifference:totalWeight,// 总重差
        goodsCount,// 数量
        totalWeight,// 总重
        weigh:'',
        userNames
      })
      console.log(
        encasement
      );
      this.encasementList.push()
    }
  },
  computed: {
    containerNumberList() {
      return this.goodsList
        .filter(item => item.containerNumber)
        .map(item => item.containerNumber)
    },
    busDateFormat(){
      const {busDate} = this.pageData
      return busDate ?wx.$timeFormat(busDate) : '' // new Date(busDate).$format('dd/MM/yyyy') : ''
    },
    sectionalCabinetTimeFormat(){
      const {sectionalCabinetTime:time} = this.pageData
      return time ? wx.$timeFormat(time) : '' //new Date(time).$format('dd/MM/yyyy') : ''
    },
    departTimeFormat(){
      const {departTime} = this.pageData
      return departTime ? wx.$timeFormat(departTime) : '' //new Date(departTime).$format('dd/MM/yyyy') : ''
    },
    arriveTimeFormat(){
      const { arriveTime } = this.pageData
      return arriveTime ? wx.$timeFormat(arriveTime) : '' //new Date(arriveTimenew).$format('dd/MM/yyyy') : ''
    }
  },
  data() {
    return {
      adjustPosition: true,
      disabledEdit: false,
      goodsId: '',
      lang: wx.getStorageSync('lang'),
      pdt: 66, //顶部
      local: wx.getStorageSync('local'), //国际化
      pageData: {
      }, //当前页面数据
      goodsList: [], //当前页面的商品数据
      encasementList: [], //物流信息
       containerNumberList: [],
      arrayWood: [
        { value: 1,label: '无' },
        { value: 2,label: '有'}],
      Shop,
      goodsCount: 1,
      indexContainerPicker: 0,
      indexWoodPicker: 0,
      logisticsDetail: {},
      logisticsObj: [],
      files: [],
      indexPicker: 1,
      logs: [],
      fileList: []
    }
  },
  onLoad(options) {
    this.initLang()
    this.pdt = this.globalData.CustomBar
    this.affirmLogistics(options.id)
    this.getPageData(options)
  },
  onShow() {
    this.initLang()

    if (a) {
      a = false
      return
    } else {
      // 上一页返回的数据
      this.prevPage()
    }


  }
}
</script>

<style scoped lang="scss">
@import 'index';
.log-list {
  display: flex;
  flex-direction: column;
  padding: 40rpx;
}

.log-item {
  margin: 10rpx;
}
</style>
